package com.yntsoft.realm;

import java.util.concurrent.atomic.AtomicInteger;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;

import com.yntsoft.util.EhcacheUtil;


//散列凭证匹配器
public class RetryLimitCredentialsMatcher extends HashedCredentialsMatcher {
	
	private EhcacheUtil ehcacheUtil;
	
	/* 
	 * 做凭证匹配
	 * (non-Javadoc)
	 * @see org.apache.shiro.authc.credential.HashedCredentialsMatcher#doCredentialsMatch(org.apache.shiro.authc.AuthenticationToken, org.apache.shiro.authc.AuthenticationInfo)
	 */
	@Override
	public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
		String userName = (String) token.getPrincipal();
		ehcacheUtil = EhcacheUtil.getInstance();
		AtomicInteger atomicInteger = null;
		Object retryCount = ehcacheUtil.get(userName, "retryCount");
		if( null == retryCount ){
			atomicInteger = new AtomicInteger(1);
		}else{
			atomicInteger = (AtomicInteger)retryCount;
			if(atomicInteger.incrementAndGet() > 5){//以原子方式+1
				throw new ExcessiveAttemptsException("密码错误次数超过5次，请2小时候在试");
			}
		}
		ehcacheUtil.put(userName,"retryCount" , atomicInteger);
		boolean matches = super.doCredentialsMatch(token, info);
		if(matches){//登陆成功
			ehcacheUtil.remove(userName,"retryCount");
		}
		return matches;
	}
}